import os
import sys
import uuid

from src.base.settings import Settings
from src.conf.base_conf import BaseConf


class Conf(BaseConf):
    def __init__(self, path: str):
        """主配置文件"""
        super().__init__(path)

    def _reload_from_dict(self, conf_dict: dict):  # pragma: no cover
        self.version = conf_dict.get("程序版本", Settings.COMPATIBLE_VERSIONS[-1])
        self.detail = conf_dict.get("描述", "DLS基本的配置项在此处修改")
        self.__exe_cmd = conf_dict.get("开服命令", "bedrock_server.exe")
        self.exe_stop_cmd = conf_dict.get("关服命令", "stop")
        self.exe_stop_wait = conf_dict.get("关服时限", 30)
        self.exe_re_alive = conf_dict.get("崩溃重启", True)
        self.exe_re_alive_limit = conf_dict.get("连续崩溃时限", 180)
        self.output_shield = conf_dict.get("输出屏蔽",
                                           ["Running AutoCompaction...", "A previous save has not been completed."])
        self.limit_dls_cmd = conf_dict.get("禁用内置命令", ["sys"])
        self.show_dls_execute = conf_dict.get("显示执行命令", True)
        self.server_port = conf_dict.get("服务端口", 0)
        self.server_token = conf_dict.get("服务token", str(uuid.uuid4()))
        # windows中分割路径切换目录
        if Settings.OS_PLATFORM == 'Windows':
            self.exe_dir, self.exe_name = os.path.split(self.__exe_cmd)
        else:  # Darwin(macOS)与linux中路径分割存在问题
            self.exe_dir = "."
            self.exe_name = self.__exe_cmd

    def _check(self):  # pragma: no cover
        # 检查版本
        if self.version not in Settings.COMPATIBLE_VERSIONS:
            input("[DLS][WARN] 配置文件版本过低，请使用新版再运行程序")
            sys.exit()
        if not self.__exe_cmd:
            input("[DLS][WARN] 开服命令不能为空，请修改后重启程序")
            sys.exit()
        # 输出屏蔽异常处理
        if type(self.output_shield) is not list:
            self.output_shield = []
            print("[DLS][WARN] 输出屏蔽格式异常！此功能将被禁用")

    def __str__(self) -> str:
        conf_dict = {
            "程序版本": self.version,
            "开服命令": self.__exe_cmd,
            "关服命令": self.exe_stop_cmd,
            "关服时限": self.exe_stop_wait,
            "崩溃重启": self.exe_re_alive,
            "连续崩溃时限": self.exe_re_alive_limit,
            "输出屏蔽": self.output_shield,
            "禁用内置命令": self.limit_dls_cmd,
            "显示执行命令": self.show_dls_execute,
            "服务端口": self.server_port,
            "服务token": self.server_token,
            "描述": self.detail
        }
        return self._dict_to_str(conf_dict)
